package com.htx.zqs.blesmartmask.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.PermissionChecker;
import android.test.mock.MockContext;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.OKData;
import com.htx.zqs.blesmartmask.bean.VersionInfo;
import com.htx.zqs.blesmartmask.custom.CTextView;
import com.htx.zqs.blesmartmask.custom.CommonProgressDialog;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.service.ProcessMainService;
import com.htx.zqs.blesmartmask.service.UpTimesService;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.FileLogUtils;
import com.htx.zqs.blesmartmask.utils.Logger;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Tools;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zhao on 2018/6/13.
 */

public class SplashActivity extends BaseActivity {

    private static final String ACTIVITY_ALIAS_1 = "com.htx.zqs.blesmartmask.ActivityAlias1";
    private static final String ACTIVITY_ALIAS_2 = "com.htx.zqs.blesmartmask.ActivityAlias2";
    private static final int REQUEST_ENABLE_BT = 700;
    @InjectView(R.id.version_code)
    CTextView versionCode;
    @InjectView(R.id.welcome)
    CTextView welcome;
    private BluetoothAdapter bluetoothAdapter;
    private boolean isCommitInfo;
    private CommonProgressDialog pBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }
        Intent intent = new Intent(getApplicationContext(), ProcessMainService.class);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
        MySpUtils.putBoolean(MySpUtils.KEY_END_COURSE_TEST, false);
        String versionName = Tools.getVersionName(this);
        setContentView(R.layout.splash_activity);
        ButterKnife.inject(this);
//        if ((Boolean) (SPUtil.get(this,"isFirstRun",true,"isFirstRun"))){
//           restart();
//        }
        initView(versionName);

        isCommitInfo = (boolean) SPUtil.get(this, "isCommitInfo", false, "isCommitInfo");
        if (!BlEUtile.isNetworkConnected(this)) {
            requestPermissions();
        } else {
            String currentTime = BlEUtile.getCurrentTime();
            Log.e("======", currentTime);
            boolean isGetVersionToday = (boolean) SPUtil.get(this, currentTime, false, "isGetVersionToday");
            if (!isGetVersionToday) {
                //  if (true) {
                int vision = Tools.getVersion(this);
                Log.e("=====", "版本更新==" + vision);
                getVersion(vision);
                SPUtil.clear(this, "isGetVersionToday");
            } else {
                requestPermissions();
            }

        }
        //动态切换桌面图标和文字
        // setIcon(ACTIVITY_ALIAS_1);

    }

    private void initView(String vision) {
        versionCode = findViewById(R.id.version_code);
        versionCode.setText(("VISION：" + vision),
                AnimationUtils.loadAnimation(this, R.anim.ctext_alpha), 2000, 20, getResources().getColor(R.color.blue));
        welcome.setText("Welcome  to  Join  us", AnimationUtils.loadAnimation
                (this, R.anim.ctext_fly_in), 2000, 23, getResources().getColor(R.color.blue));
    }

    private void setIcon(String activity_alias) {
        Context ctx = getApplication();
        PackageManager pm = ctx.getPackageManager();
        // 使ACTIVITY_ALIAS_1失效
        pm.setComponentEnabledSetting(
                new ComponentName(ctx, ACTIVITY_ALIAS_1),
                ACTIVITY_ALIAS_1.equals(activity_alias) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        // 使ACTIVITY_ALIAS_2生效
        pm.setComponentEnabledSetting(
                new ComponentName(ctx, ACTIVITY_ALIAS_2),
                ACTIVITY_ALIAS_2.equals(activity_alias) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);

        Log.e("TAG", "setIcon----success!!");
        //干掉桌面app，让它自动重启。
        ActivityManager am = (ActivityManager) ctx.getSystemService(Activity.ACTIVITY_SERVICE);
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.addCategory(Intent.CATEGORY_HOME);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        List<ResolveInfo> resolves = pm.queryIntentActivities(i, 0);
        for (ResolveInfo res : resolves) {
            if (res.activityInfo != null) {
                am.killBackgroundProcesses(res.activityInfo.packageName);
            }
        }
    }

    // 下载存储的文件名
    private static final String DOWNLOAD_NAME = "channelWe";

    // 获取更新版本号
    private void getVersion(final int vision) {
//         {"data":{"content":"其他bug修复。","id":"2","api_key":"android",
//         // "version":"2.1"},"msg":"获取成功","status":1}
        final String data = "";
        //网络请求获取当前版本号和下载链接
        OkhttpUtils okhttpUtils = new OkhttpUtils(this, 406, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {
                Log.e("=====", "网络请求==" + string);
                //实际操作是从服务器获取
                String currentTime = BlEUtile.getCurrentTime();
                SPUtil.put(SplashActivity.this, currentTime, true, "isGetVersionToday");
                //  boolean isGetVersionToday = (boolean) SPUtil.get(this, currentTime, false, "isGetVersionToday");
                //demo写死了
                Gson gson = new Gson();
                OKData okData = gson.fromJson(string, OKData.class);
                Log.e("=====", "网络请求==11" + okData);
                // VersionInfo versionInfo = gson.fromJson(okData.getData(), VersionInfo.class);
                // Log.e("=====", "网络请求22==" + versionInfo);
                VersionInfo versionInfo = okData.getVersionInfo();
                if (versionInfo != null) {
                    String newversion = versionInfo.getVersioncode() + "";//更新新的版本号
//                String content = "\n" +
//                        "就不告诉你我们更新了什么-。-\n" +
//                        "\n" +
//                        "----------万能的分割线-----------\n" +
//                        "\n" +
//                        "(ㄒoㄒ) 被老板打了一顿，还是来告诉你吧：\n" +
//
//                        "1.下架商品误买了？恩。。。我搞了点小动作就不会出现了\n" +
//                        "2.侧边栏、弹框优化 —— 这个你自己去探索吧，总得留点悬念嘛-。-\n";//更新内容
                    String s = versionInfo.getVersionstateone();
                    String s1 = versionInfo.getVersionstattwo();
                    String s2 = versionInfo.getVersionstatethree();

                    if (s == null) {
                        s = "";
                    } else if (s1 == null) {
                        s1 = "";
                    } else if (s2 == null) {
                        s2 = "";
                    }

                    String content = "\n" + getResources().getString(R.string.version_name) + "：" + versionInfo.getVersionname() +
                            "\n" + "\n" + getResources().getString(R.string.version_size) + " ：" + versionInfo.getVersionsize() + "\n" + "\n"
                            + getResources().getString(R.string.update_content) + " ：\n\n" + "\u3000\u3000" + s +
                            "\n" + "\n" + "\u3000\u3000" + s1 + "\n" +
                            "\n" + "\u3000\u3000" + s2 + "\n";
                    String url = versionInfo.getDownloadurl();
                    Log.e("=====", "网络请求==12" + url);
                    double newversioncode = Double
                            .parseDouble(newversion);
                    int cc = (int) (newversioncode);

//                    System.out.println(newversion + "v" + vision + ",,"
//                            + cc);
                    if (cc != vision) {
                        if (vision < cc) {
                            System.out.println(newversion + "v"
                                    + vision);
                            // 版本号不同
                            ShowDialog(vision, newversion, content, url);
                            Log.e("=====", "网络请求==216" + url);
                        } else {
                            requestPermissions();
                        }
                    } else {
                        requestPermissions();
                    }
                } else {
                    requestPermissions();
                }
            }

            @Override
            public void onError(int requestCode, IOException e) {
                Log.e("==========", e + "==");
                requestPermissions();
            }
        });
        HashMap hashMap = new HashMap();
        hashMap.put("vercode", 1);
        hashMap.put("islogo", "A");
        hashMap.put("language", BlEUtile.getLanguage());
        //okhttpUtils.get(406,Contants.BASE_URL+"Versions.link");
        Log.e("=====", "网络请求==" + hashMap);
        okhttpUtils.postForm(406, Contants.BASE_URL + "Versions.link", hashMap);
        Log.e("=====", "网络请求==" + 11111);
    }

    /**
     * 升级系统
     *
     * @param content
     * @param url
     */
    private void ShowDialog(int vision, String newversion, String content,
                            final String url) {
//        final MaterialDialog dialog = new MaterialDialog(this);//自定义的对话框，可以呀alertdialog
//        dialog.content(content).btnText("取消", "更新").title("版本更新 ")
//                .titleTextSize(15f).show();
//        dialog.setCanceledOnTouchOutside(false);
//        dialog.setOnBtnClickL(new OnBtnClickL() {// left btn click listener
//            @Override
//            public void onBtnClick() {
//                dialog.dismiss();
//            }
//        }, new OnBtnClickL() {// right btn click listener
//
//            @Override
//            public void onBtnClick() {
//                dialog.dismiss();
//                // pBar = new ProgressDialog(MainActivity.this,
//                // R.style.dialog);
//                pBar = new CommonProgressDialog(MainActivity.this);
//                pBar.setCanceledOnTouchOutside(false);
//                pBar.setTitle("正在下载");
//                pBar.setCustomTitle(LayoutInflater.from(
//                        MainActivity.this).inflate(
//                        R.layout.title_dialog, null));
//                pBar.setMessage("正在下载");
//                pBar.setIndeterminate(true);
//                pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//                pBar.setCancelable(true);
//                // downFile(URLData.DOWNLOAD_URL);
//                final DownloadTask downloadTask = new DownloadTask(
//                        MainActivity.this);
//                downloadTask.execute(url);
//                pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//                        downloadTask.cancel(true);
//                    }
//                });
//            }
//        });

        new android.app.AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.version_update))
                .setMessage(content)
                .setPositiveButton(getResources().getString(R.string.update), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pBar = new CommonProgressDialog(SplashActivity.this);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle(getResources().getString(R.string.downloading));
                        pBar.setCustomTitle(LayoutInflater.from(
                                SplashActivity.this).inflate(
                                R.layout.title_dialog, null));
                        pBar.setMessage(getResources().getString(R.string.downloading));
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(true);
                        // downFile(URLData.DOWNLOAD_URL);
                        final DownloadTask downloadTask = new DownloadTask(
                                SplashActivity.this);
                        downloadTask.execute(url);
                        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                downloadTask.cancel(true);
                                requestPermissions();
                            }
                        });
                    }
                })
                .setCancelable(false)
                .setNegativeButton(getResources().getString(R.string.cancle), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestPermissions();
                    }
                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //requestPermissions();
            }
        })
                .show();

    }

    /**
     * 下载应用
     *
     * @author Administrator
     */
    class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error
                // report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    file = new File(Environment.getExternalStorageDirectory(),
                            DOWNLOAD_NAME);

                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(SplashActivity.this, getResources().getString(R.string.sd_not_mounted),
                            Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            pBar.dismiss();
            if (result != null) {

//                // 申请多个权限。大神的界面
//                AndPermission.with(MainActivity.this)
//                        .requestCode(REQUEST_CODE_PERMISSION_OTHER)
//                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
//                        // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
//                        .rationale(new RationaleListener() {
//                                       @Override
//                                       public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
//                                           // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
//                                           AndPermission.rationaleDialog(MainActivity.this, rationale).show();
//                                       }
//                                   }
//                        )
//                        .send();
                // 申请多个权限。
                AndPermission.with(SplashActivity.this)
                        .requestCode(REQUEST_CODE_PERMISSION_SD)
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

                        // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
                        .rationale(rationaleListener
                        )
                        .send();


                Toast.makeText(context, R.string.sd_not_permissions + result, Toast.LENGTH_LONG).show();
            } else {
                // Toast.makeText(context, "File downloaded",
                // Toast.LENGTH_SHORT)
                // .show();
                update();
            }

        }

    }

    private static final int REQUEST_CODE_PERMISSION_SD = 101;

    private static final int REQUEST_CODE_SETTING = 300;
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            // 这里使用自定义对话框，如果不想自定义，用AndPermission默认对话框：
            // AndPermission.rationaleDialog(Context, Rationale).show();

            // 自定义对话框。
            AlertDialog.build(SplashActivity.this)
                    .setTitle(R.string.title_dialog)
                    .setMessage(R.string.message_permission_rationale)
                    .setPositiveButton(R.string.btn_dialog_yes_permission, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();
                        }
                    })

                    .setNegativeButton(R.string.btn_dialog_no_permission, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel();
                        }
                    })
                    .show();
        }
    };
    //----------------------------------SD权限----------------------------------//


    @PermissionYes(REQUEST_CODE_PERMISSION_SD)
    private void getMultiYes(List<String> grantedPermissions) {
        Toast.makeText(this, R.string.message_post_succeed, Toast.LENGTH_SHORT).show();
    }

    @PermissionNo(REQUEST_CODE_PERMISSION_SD)
    private void getMultiNo(List<String> deniedPermissions) {
        Toast.makeText(this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();

        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                    .setTitle(R.string.title_dialog)
                    .setMessage(R.string.message_permission_failed)
                    .setPositiveButton(R.string.btn_dialog_yes_permission)
                    .setNegativeButton(R.string.btn_dialog_no_permission, null)
                    .show();

            // 更多自定dialog，请看上面。
        }
    }

    //----------------------------------权限回调处理----------------------------------//

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        /**
         * 转给AndPermission分析结果。
         *
         * @param object     要接受结果的Activity、Fragment。
         * @param requestCode  请求码。
         * @param permissions  权限数组，一个或者多个。
         * @param grantResults 请求结果。
         */

        Log.e("======", "============");
        // start(isCommitInfo, Contants.SPLASH_TIME-1000);
        try {
            AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        } catch (Exception e) {

        } finally {
            initBLE();
        }
    }

    private int aaa = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SETTING: {
                Toast.makeText(this, R.string.message_setting_back, Toast.LENGTH_LONG).show();
                //设置成功，再次请求更新
                getVersion(Tools.getVersion(SplashActivity.this));
                break;
            }
            case 450:
                if (resultCode != RESULT_OK) {
                    // setIcon(ACTIVITY_ALIAS_2);
                    requestPermissions();
                }
                break;
            case REQUEST_ENABLE_BT:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this, R.string.main_bluetooth_on, Toast.LENGTH_LONG).show();
                    start(isCommitInfo, Contants.SPLASH_TIME);
                } else {
                    aaa++;
                    if (aaa == 1 || aaa == 2) {
                        new android.support.v7.app.AlertDialog.Builder(this).setTitle(R.string.title_dialog)
                                .setMessage(R.string.splash_dialog_message)
                                .setNegativeButton(R.string.ok, null)
                                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        dialog.dismiss();
                                        initBLE();
                                    }
                                })
                                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialog) {
                                    }
                                }).show();
                    } else {
                        finish();
                    }
                }
        }
    }


    private void update() {
        //安装应用

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        File file = new File(Environment
                .getExternalStorageDirectory(), DOWNLOAD_NAME);
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(this, "com.htx.photo", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        startActivityForResult(intent, 450);
    }

    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (isCheck(Manifest.permission.READ_PHONE_STATE)) {
                // 未授权
                //  此处动态申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA, Manifest.permission.WRITE_SETTINGS}, 235);
            } else if (isCheck(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION}, 236);
            } else if (isCheck(Manifest.permission.CAMERA)) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.CAMERA}, 237);
            } else if (isCheck(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 238);
                return;
            } else {
                initBLE();
            }
        } else {
            initBLE();
        }
    }

    private boolean isCheck(String string) {
        return ContextCompat.checkSelfPermission(this,
                string) != PermissionChecker.PERMISSION_GRANTED;
    }

    private void initBLE() {   // 开启蓝牙
        bluetoothAdapter = BlEUtile.getBleAdapter();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
//                bluetoothAdapter.enable();
//                Toast.makeText(this,R.string.main_bluetooth_on, Toast.LENGTH_SHORT).show();

                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            } else {
                start(isCommitInfo, Contants.SPLASH_TIME - 1000);
            }
        }
//        boolean b = BlEUtile.checkLocatoinPermission(this);
//        if (b){
//            Toast.makeText(this,"nihaoma",Toast.LENGTH_LONG).show();
//        }
    }

    private void start(boolean isCommitInfo, int time) {
        if (!isCommitInfo) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    Intent intent = new Intent(SplashActivity.this, OrderInfoActivity.class);
                    startActivity(intent);
                    finish();
                }
            }, time);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }, time);
        }
    }
}
